package org.example.struct.array2;

import com.alibaba.fastjson2.JSON;

import java.util.*;

/**
 * @author liyishan
 * @date 2023/10/19 10:11
 * @apiNote
 */

public class Test00870AdvantageCount {

    public static void main(String[] args) {
        int[] nums1 = {2,0,4,1,2};
        int[] nums2 = {1,3,0,0,2};
        int[] res = test(nums1, nums2);
        System.out.println(JSON.toJSON(res));
    }

    public static int[] test(int[] nums1, int[] nums2) {
        int n = nums1.length;
        TreeSet<Integer> test = new TreeSet<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int x : nums1) {
            map.put(x, map.getOrDefault(x, 0) + 1);
            if(map.get(x) == 1){
                test.add(x);
            }
        }
        int[] ans = new int[n];
        for(int i = 0; i < n; i++){
            Integer cur = test.ceiling(nums2[i]+1);
            if(cur == null){
                cur = test.ceiling(-1);
            }
            ans[i] = cur;
            map.put(cur,map.get(cur) -1);
            if(map.get(cur) == 0){
                test.remove(cur);
            }
        }
        return ans;
    }
}
